<template>
  <div class="todo-list">
    <div class="list-header">
      <h3 class="list-title">待办事项</h3>
      <div class="list-actions">
        <el-text size="small" type="info">
          Space 完成，Delete 删除
        </el-text>
      </div>
    </div>
    
    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="3" animated />
    </div>
    
    <div v-else-if="todos.length === 0" class="empty-container">
      <el-empty description="暂无待办事项" :image-size="120">
        <template #description>
          <p>还没有添加任何待办事项</p>
          <p>快去添加一个吧！</p>
        </template>
      </el-empty>
    </div>
    
    <div v-else class="todo-items">
      <!-- 渲染分组的待办事项 -->
      <div v-for="group in groupedTodos" :key="group.type" class="todo-group">
        <!-- 分组标题 -->
        <div v-if="group.todos.length > 0" class="group-header">
          <h4 class="group-title">
            <el-icon class="group-icon">
              <component :is="group.icon" />
            </el-icon>
            {{ group.title }}
            <el-badge :value="group.todos.length" class="group-count" />
          </h4>
        </div>
        
        <!-- 该分组的待办事项 -->
        <div 
          v-for="todo in group.todos" 
          :key="todo.id"
          class="todo-item"
          :class="{ 
            completed: todo.completed,
            overdue: isOverdue(todo)
          }"
          @keydown="handleKeydown($event, todo)"
          tabindex="0"
        >
        <div class="todo-content">
          <div class="todo-checkbox">
            <el-checkbox 
              :model-value="todo.completed"
              @change="handleComplete(todo.id)"
              size="large"
            />
          </div>
          
          <div class="todo-info">
            <div class="todo-title" :class="{ completed: todo.completed }">
              {{ todo.title }}
            </div>
            
            <div class="todo-datetime">
              <el-icon class="meta-icon"><Calendar /></el-icon>
              <span>{{ formatDate(todo.dueDate) }}</span>
              <template v-if="todo.dueTime">
                <el-icon class="meta-icon"><Clock /></el-icon>
                <span>{{ todo.dueTime }}</span>
              </template>
            </div>
          </div>
        </div>
        
        <div class="todo-status">
          <el-tag 
            v-if="isOverdue(todo) && !todo.completed"
            type="danger" 
            size="small"
            effect="plain"
          >
            已过期
          </el-tag>
          <el-tag 
            v-else-if="isToday(todo.dueDate)"
            type="primary" 
            size="small"
            effect="plain"
          >
            今日
          </el-tag>
          <el-tag 
            v-else-if="isTomorrow(todo.dueDate)"
            type="success" 
            size="small"
            effect="plain"
          >
            明日
          </el-tag>
        </div>
        
        <div class="todo-countdown" v-if="!todo.completed && todo.dueTime">
          <div class="countdown-text">
            {{ getCountdown(todo.dueDate, todo.dueTime) }}
          </div>
        </div>
        
        <div class="todo-actions">
          <el-button
            type="primary"
            text
            size="small"
            @click="handleEdit(todo)"
            class="action-btn"
          >
            <el-icon><Edit /></el-icon>
          </el-button>
          
          <el-button
            type="danger"
            text
            size="small"
            @click="handleDelete(todo.id)"
            class="action-btn"
          >
            <el-icon><Delete /></el-icon>
          </el-button>
        </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { computed } from 'vue'
import { Calendar, Clock, Edit, Delete, CircleCheck, List } from '@element-plus/icons-vue'
import { checkIsToday, checkIsTomorrow, formatDate, getCountdown } from '../utils/date'
import dayjs from 'dayjs'

export default {
  name: 'TodoList',
  components: {
    Calendar,
    Clock,
    Edit,
    Delete,
    CircleCheck,
    List
  },
  props: {
    todos: {
      type: Array,
      default: () => []
    },
    loading: {
      type: Boolean,
      default: false
    }
  },
  emits: ['complete', 'delete', 'edit'],
  setup(props, { emit }) {
    const handleComplete = (todoId) => {
      emit('complete', todoId)
    }
    
    const handleDelete = (todoId) => {
      emit('delete', todoId)
    }
    
    const handleEdit = (todo) => {
      emit('edit', todo)
    }
    
         const isOverdue = (todo) => {
       if (todo.completed) return false
       const now = dayjs()
       const todoDateTime = dayjs(`${todo.dueDate} ${todo.dueTime || '23:59'}`)
       return todoDateTime.isBefore(now)
     }
    
    const isToday = (date) => {
      return checkIsToday(date)
    }
    
    const isTomorrow = (date) => {
      return checkIsTomorrow(date)
    }
    
    const handleKeydown = (event, todo) => {
      if (event.code === 'Space') {
        event.preventDefault()
        handleComplete(todo.id)
      } else if (event.code === 'Delete') {
        event.preventDefault()
        handleDelete(todo.id)
      }
    }
    
    // 分组待办事项：待完成和已完成
    const groupedTodos = computed(() => {
      const pending = props.todos.filter(todo => !todo.completed)
      const completed = props.todos.filter(todo => todo.completed)
      
      const groups = []
      
      // 待完成分组
      if (pending.length > 0) {
        groups.push({
          type: 'pending',
          title: '待完成',
          icon: 'List',
          todos: pending.sort((a, b) => {
            // 按截止时间排序
            const aTime = `${a.dueDate} ${a.dueTime || '23:59'}`
            const bTime = `${b.dueDate} ${b.dueTime || '23:59'}`
            return aTime.localeCompare(bTime)
          })
        })
      }
      
      // 已完成分组
      if (completed.length > 0) {
        groups.push({
          type: 'completed',
          title: '已完成',
          icon: 'CircleCheck',
          todos: completed.sort((a, b) => {
            // 按完成时间降序
            const aCompleted = a.completedAt || a.updateTime || a.createTime
            const bCompleted = b.completedAt || b.updateTime || b.createTime
            return new Date(bCompleted) - new Date(aCompleted)
          })
        })
      }
      
      return groups
    })
    
    return {
      handleComplete,
      handleDelete,
      handleEdit,
      handleKeydown,
      isOverdue,
      isToday,
      isTomorrow,
      formatDate,
      getCountdown,
      groupedTodos
    }
  }
}
</script>

<style scoped>
.todo-list {
  background: var(--el-bg-color);
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 1px solid var(--el-border-color-lighter);
}

.list-title {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: var(--el-text-color-primary);
}

.loading-container {
  padding: 20px 0;
}

.empty-container {
  padding: 40px 20px;
}

.todo-items {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.todo-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.group-header {
  margin-bottom: 8px;
}

.group-title {
  display: flex;
  align-items: center;
  gap: 8px;
  margin: 0;
  font-size: 14px;
  font-weight: 600;
  color: var(--el-text-color-regular);
  padding: 8px 0;
  border-bottom: 1px solid var(--el-border-color-lighter);
}

.group-icon {
  font-size: 16px;
  color: var(--el-color-primary);
}

.group-count {
  margin-left: auto;
}

.todo-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 16px;
  border-radius: 8px;
  border: 1px solid var(--el-border-color-lighter);
  background: var(--el-fill-color-extra-light);
  transition: all 0.2s ease;
  cursor: pointer;
}

.todo-item:hover {
  border-color: var(--el-color-primary-light-5);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.todo-item:focus {
  outline: none;
  border-color: var(--el-color-primary);
  box-shadow: 0 0 0 2px var(--el-color-primary-light-8);
}

.todo-item.completed {
  opacity: 0.7;
  background: var(--el-fill-color);
}

.todo-item.overdue {
  border-color: var(--el-color-danger-light-5);
  background: var(--el-color-danger-light-9);
}

.todo-content {
  display: flex;
  align-items: center;
  gap: 12px;
  flex: 1;
}

.todo-checkbox {
  flex-shrink: 0;
}

.todo-info {
  flex: 1;
  min-width: 0;
}

.todo-title {
  font-size: 16px;
  font-weight: 500;
  color: var(--el-text-color-primary);
  margin-bottom: 4px;
  word-break: break-word;
}

.todo-title.completed {
  text-decoration: line-through;
  color: var(--el-text-color-secondary);
}

.todo-datetime {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
  color: var(--el-text-color-regular);
}

.meta-icon {
  font-size: 12px;
}

.todo-status {
  display: flex;
  align-items: center;
  gap: 4px;
  flex-shrink: 0;
}

.todo-countdown {
  flex-shrink: 0;
  text-align: right;
}

.countdown-text {
  font-size: 12px;
  color: var(--el-text-color-regular);
  font-weight: 500;
}

.todo-actions {
  display: flex;
  gap: 4px;
  flex-shrink: 0;
  opacity: 0;
  transition: opacity 0.2s ease;
}

.todo-item:hover .todo-actions {
  opacity: 1;
}

.action-btn {
  padding: 4px;
  min-height: auto;
}

@media (max-width: 768px) {
  .todo-item {
    flex-direction: column;
    align-items: stretch;
    gap: 12px;
  }
  
  .todo-content {
    flex-direction: column;
    align-items: stretch;
    gap: 8px;
  }
  
  .todo-status {
    justify-content: flex-start;
  }
  
  .todo-countdown {
    text-align: left;
  }
  
  .todo-actions {
    opacity: 1;
    justify-content: center;
  }
}
</style> 